package com.llkj.contractmanagement.contractmanagement.contract;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.github.promeg.pinyinhelper.Pinyin;
import com.llkj.contractmanagement.main.BaseFragment;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.contractmanagement.adapter.ContractMovieAdapter;
import com.llkj.contractmanagement.customview.SideBar;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.main.MyApplication;
import com.llkj.contractmanagement.model.ContractBean;
import com.llkj.contractmanagement.model.MovieContractBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.CharacterParser;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.LogUtil;
import com.llkj.contractmanagement.utils.Pinyin4jUtil;
import com.llkj.contractmanagement.utils.PinyinComparator;
import com.llkj.contractmanagement.utils.ToastUtil;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * author: dong.yj
 * created on: 2016/8/16 16:04
 * description:合同-影视界面
 */
public class MovieFragment extends BaseFragment implements SideBar.OnTouchingLetterChangedListener, AdapterView.OnItemClickListener, BGARefreshLayout.BGARefreshLayoutDelegate, AdapterView.OnItemLongClickListener {

    @Bind(R.id.bga_refresh)
    BGARefreshLayout bgaRefreshLayout;
    @Bind(R.id.lv_contract_movie)
    ListView lvContractMovie;
    @Bind(R.id.dialog)
    TextView dialog;
    @Bind(R.id.sidrbar_contract_movie)
    SideBar sideBar;
    //    根据拼音来排列ListView里面的数据类
    private PinyinComparator pinyinComparator;
    private List<MovieContractBean.HtlistBean> movieContractList;
    private ContractMovieAdapter adapter;
    //    汉字转换成拼音的类
//    private CharacterParser characterParser;

    @Override
    public int getContentViewLayout() {
        return R.layout.fragment_contract_movie;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init() {
        initData();
        setListener();

    }

    private void setListener() {
        bgaRefreshLayout.setDelegate(this);
        sideBar.setTextView(dialog);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(this);
        lvContractMovie.setOnItemClickListener(this);
        lvContractMovie.setOnItemLongClickListener(this);
    }

    private void initData() {
        bgaRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));
        // 实例化汉字转拼音类
//        characterParser = CharacterParser.getInstance();
        movieContractList = new ArrayList<>();
        //根据拼音来排列ListView里面的数据类
        pinyinComparator = new PinyinComparator();
//        contractBeanList = filledData(getResources().getStringArray(R.array.date));
        adapter = new ContractMovieAdapter(ctx, movieContractList);
        lvContractMovie.setAdapter(adapter);

        requestData();
    }

    private void requestData() {
        UserInfoBean userInfoBean = UserInfoBean.getInstance();
        HashMap<String, String> map = new HashMap<>();
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        HttpMethod.ysList(this, ctx, map, UrlConfig.HTTP_YS_LIST);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        // 该字母首次出现的位置
        int position = adapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
            lvContractMovie.setSelection(position);
        }
    }

//    /**
//     * 为ListView填充数据
//     *
//     * @param date
//     * @return
//     */
//    private List<ContractBean> filledData(String[] date) {
//        List<ContractBean> mSortList = new ArrayList<ContractBean>();
//
//        for (int i = 0; i < date.length; i++) {
//            ContractBean sortModel = new ContractBean();
//            sortModel.setName(date[i]);
//            // 汉字转换成拼音
//            String pinyin = characterParser.getSelling(date[i]);
//            String sortString = pinyin.substring(0, 1).toUpperCase();
//            // 正则表达式，判断首字母是否是英文字母
//            if (sortString.matches("[A-Z]")) {
//                sortModel.setSortLetters(sortString.toUpperCase());
//            } else {
//                sortModel.setSortLetters("#");
//            }
//
//            mSortList.add(sortModel);
//        }
//        return mSortList;
//
//    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MovieContractBean.HtlistBean htlistBean = movieContractList.get(position);
        if (htlistBean.getFl() == 1) {
            Intent intent = new Intent(ctx, ChildrenContractClassifyActivity.class);
            intent.putExtra("type", 0);
            intent.putExtra("fl_id", htlistBean.getHt_id());
            intent.putExtra("title", htlistBean.getName());
            startActivity(intent);
        } else if (htlistBean.getFl() == 0) {
            Intent intent = new Intent(ctx, ContractListActivity.class);
            intent.putExtra("fl_id", htlistBean.getHt_id());
            intent.putExtra("title", htlistBean.getName());
            startActivity(intent);
        }

    }

    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        switch (resultCode) {
            case UrlConfig.HTTP_YS_LIST://影视合同列表
                bgaRefreshLayout.endRefreshing();
                MovieContractBean movieContractBean = GsonUtil.GsonToBean(responseInfo, MovieContractBean.class);
                if (movieContractBean != null) {
                    List<MovieContractBean.HtlistBean> addList = movieContractBean.getHtlist();
                    if (addList.size() > 0 && addList != null) {
                        for (int i = 0; i < addList.size(); i++) {
                            // 汉字转换成拼音
//                            String pinyin = characterParser.getSelling(addList.get(i).getName());
                            String name = addList.get(i).getName();
                            if (!TextUtils.isEmpty(name)) {
//                                String pinyin = Pinyin4jUtil.converterToSpell(name.substring(0, 1));
//                                String pinyin = characterParser.getSelling(name);
                                String pinyin = Pinyin.toPinyin(name,"");
                                if (TextUtils.isEmpty(pinyin)) {
                                    addList.get(i).setSortLetters("#");
                                } else {
                                    String sortString = pinyin.substring(0, 1).toUpperCase();
                                    LogUtil.e("pinyinshouzimu-" + pinyin);
                                    // 正则表达式，判断首字母是否是英文字母
                                    if (sortString.matches("[A-Z]")) {
                                        addList.get(i).setSortLetters(sortString);
                                    } else {
                                        addList.get(i).setSortLetters("#");
                                    }
                                }
                            } else {
                                addList.get(i).setSortLetters("#");
                            }
                        }
                        movieContractList.addAll(addList);
                        // 根据a-z进行排序源数据
                        Collections.sort(movieContractList, pinyinComparator);
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
        }
    }

//    public String getPinYin(String s) {
//        String pinyin = "";
//        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//        for (int i = 0; i < s.length(); i++) {
//            char c = s.charAt(i);
//            String[] vals = new String[0];
//            try {
//                vals = PinyinHelper.toHanyuPinyinStringArray(c, format);
//            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
//                badHanyuPinyinOutputFormatCombination.printStackTrace();
//            }
//            pinyin = Arrays.toString(vals);
//        }
//        return pinyin;
//    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        onRefresh();
    }

    private void onRefresh() {
        movieContractList.clear();
        requestData();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.makeShortText(getContext(), movieContractList.get(position).getName());
        return true;
    }
}
